<template>
  <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false"
             :visible.sync="showAuthDialog" append-to-body center title="该操作需要授权" width="350px" @opened="handleOpened">
    <el-form ref="userFormRef" :model="userForm" :rules="rules" :show-message="false" label-position="left" status-icon>
      <el-form-item prop="loginName">
        <el-input ref="user-name" v-model="userForm.loginName" placeholder="请输入账号"
                  @keyup.enter.native="checkAuthorized"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="userForm.password" placeholder="请输入密码" type="password"
                  @keyup.enter.native="checkAuthorized"/>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancle">取 消</el-button>
      <el-button type="warning" @click="checkAuthorized">操作授权[Enter]</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {mapGetters} from 'vuex'
import {checkPermission} from '@/api/user'
import sha256 from 'js-sha256'

export default {
  name: 'CheckAuthorize',
  props: ['showAuthDialog', 'checkKey', 'errMsg'],
  data () {
    return {
      userForm: {
        loginName: '',
        password: ''
      },
      rules: {
        loginName: [{required: true, message: '请输入用户名称', trigger: 'change'}],
        password: [{required: true, message: '请输入用户密码', trigger: 'change'}]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  mounted () {
  },
  methods: {
    checkAuthorized () {
      this.$refs['userFormRef'].validate(valid => {
        if (valid) {
          checkPermission({
            loginName: this.userForm.loginName,
            password: sha256(this.userForm.password),
            permission: this.checkKey
          }).then(res => {
            console.log(res)
            this.$message.success('授权成功')
            this.handleCancle()
            this.$emit('authPass')
          }).catch(err => {
            this.$message.warning(err)
            console.log(err)
          })
        }
      })
    },
    handleCancle () {
      this.$emit('hideAuthDialog')
      if (this.$refs['userFormRef']) {
        this.$refs['userFormRef'].resetFields()
      }
    },
    handleOpened () {
      console.log('handleOpened')
      for (var i = 0; i < this.permissions.length; i++) {
        if (this.permissions[i].path === this.checkKey) {
          this.$message.success('已有该操作权限')
          this.handleCancle()
          this.$emit('authPass')
          break
        }
      }
      this.$nextTick(() => {
        this.$refs['user-name'].focus()
      })
    }
  }
}
</script>

<style>

</style>